package com.ews.onlineexchange.service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.ews.onlineexchange.app.entity.TempServiceSupplier;
import com.ews.onlineexchange.controller.pub.ServiceSupplierListForRest;
import com.ews.onlineexchange.model.ChooseType;
import com.ews.onlineexchange.model.ServiceSupplier;
import com.ews.onlineexchange.util.SqlUtil;
@Stateless
@Named
public class ServiceSupplierService implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	//入驻起止日期
	private Date startDate;//
	private Date endDate;
	@Inject
	ServiceSupplierListForRest serviceSupplierList;
	@Inject
	EntityManager entityManager;
	
	private String FILTER_SUPPLIER_BY_CNNAME = ""
			+ " SELECT supplier 					"
			+ "	FROM ServiceSupplier supplier 				"
			+ "	WHERE supplier.delFlag = '0' 		"
			+ "	AND supplier.cnname like :cnname	";
	
	public List<ServiceSupplier> fliterSupplierByCnname(String cnname) {
		Query query = entityManager.createQuery(FILTER_SUPPLIER_BY_CNNAME).setParameter("cnname", SqlUtil.getStringRestriction(cnname));
		return query.getResultList();
	}

	private String EXIST_SUPPLIER_BY_CREDITCODE = ""
			+ " SELECT COUNT(supplier) 					"
			+ "	FROM ServiceSupplier supplier 				"
			+ "	WHERE supplier.delFlag = '0' 		"
			+ "	AND supplier.creditCode = :creditCode	";

	public boolean isExistCreditCode(String creditCode) {
		Query query = entityManager.createQuery(EXIST_SUPPLIER_BY_CREDITCODE).setParameter("creditCode", creditCode);
		Long count = (Long)query.getSingleResult();
		return count > 0;

	}

	public List<ServiceSupplier> getAudittedSupplier (Integer pageSize,Integer pageNumber,Date startDate, Date endDate, String qualificationClassId,String sectorId, String childSectorId){
		serviceSupplierList.refresh();
		serviceSupplierList.setStartDate(startDate);
		serviceSupplierList.setEndDate(endDate);
		serviceSupplierList.setQualificationClassId(qualificationClassId);
		serviceSupplierList.setSectorId(childSectorId);
		serviceSupplierList.setChildSectorId(childSectorId);
		serviceSupplierList.setFirstResult((pageNumber - 1) * pageSize);
		serviceSupplierList.setMaxResults(pageSize);
		List<ServiceSupplier> suppliers = serviceSupplierList.getResultList();
		return suppliers;
	}
	
//	//报名总次数
	private final static String GET_SUPPLIER_APPLY_COUNT_BY_ID = "	"
			+ " SELECT trade.bulletin.winnerId,trade.bulletin.wayOfChoose 									"
			+ " FROM Trade trade								"
			+ " WHERE trade.delFlag = 0							"
			+ " AND trade.apply = 1    							"
			+ " AND trade.hasVerify = 1            				"
			+ " AND trade.bulletin.tradeStatus = 'Agreed'       "
			+ "	AND trade.supplier.id = :supplierId				" ;
	public List getSupplierApplyTradeById(String supplierId) {
		return entityManager.createQuery(GET_SUPPLIER_APPLY_COUNT_BY_ID).setParameter("supplierId", supplierId).getResultList();
	}
	
	public JSONObject stat(Integer pageSize,Integer pageNumber, Date startDate,Date endDate, String qualificationClassId,String sectorId, String childSectorId){
		JSONObject json = new JSONObject();
		long start = System.currentTimeMillis();
		serviceSupplierList.refresh();
		serviceSupplierList.setStartDate(startDate);
		serviceSupplierList.setEndDate(endDate);
		serviceSupplierList.setQualificationClassId(qualificationClassId);
		serviceSupplierList.setSectorId(childSectorId);
		serviceSupplierList.setChildSectorId(childSectorId);
		if(pageSize == null )serviceSupplierList.setFirstResult(0);
		else serviceSupplierList.setFirstResult((pageNumber - 1) * pageSize);
		serviceSupplierList.setMaxResults(pageSize);
		List<ServiceSupplier> suppliers = serviceSupplierList.getResultList();
		List<TempServiceSupplier> tempSuppliers = new ArrayList<TempServiceSupplier>();
		for (ServiceSupplier serviceSupplier : suppliers) {
			String supplierId = serviceSupplier.getId();
			List appliedTrades = getSupplierApplyTradeById(supplierId);
			
			TempServiceSupplier tempSupplier = new TempServiceSupplier();
			tempSupplier.setCnname(serviceSupplier.getCnname());
			tempSupplier.setId(supplierId);
			tempSupplier.setAppliedCount((long)appliedTrades.size());
			Long  successCount = 0L;
			Long  randomSuccessCount = 0L;
			Long  bestSuccessCount = 0L;
			Long  priceSuccessCount = 0L;
			Long  averageSuccessCount = 0L;
			Long  manualSuccessCount = 0L;
			for (Object trade : appliedTrades) {
				Object[] array = (Object[])trade;
				String winnerId = (String)array[0];
				ChooseType chooseType = (ChooseType)array[1];
				if(winnerId == null)continue;
				if(winnerId.equals(supplierId)) {
					successCount ++;
					if(chooseType.equals(ChooseType.Manual))manualSuccessCount ++;
					if(chooseType.equals(ChooseType.Random))randomSuccessCount ++;
					if(chooseType.equals(ChooseType.Best))bestSuccessCount ++;
					if(chooseType.equals(ChooseType.Price))priceSuccessCount ++;
					if(chooseType.equals(ChooseType.Average))averageSuccessCount ++;
				}
			}
			tempSupplier.setSuccessCount(successCount);
			tempSupplier.setRandomSuccessCount(randomSuccessCount);
			tempSupplier.setBestSuccessCount(bestSuccessCount);
			tempSupplier.setPriceSuccessCount(priceSuccessCount);
			tempSupplier.setAverageSuccessCount(averageSuccessCount);
			tempSupplier.setManualSuccessCount(manualSuccessCount);
			tempSuppliers.add(tempSupplier);
		}
		json.put("totalCount", serviceSupplierList.getResultCount());
		json.put("list", tempSuppliers);
		long end = System.currentTimeMillis();
		System.out.println("共用时间："+(end - start) /1000);
		return json;
	}
	
	
	public Date getStartDate() {
		return startDate;
	}
	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}
	public Date getEndDate() {
		return endDate;
	}
	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}


	private static final String EXIST_CREDITCODE_EQL = ""
			+ "	SELECT			count(user)"
			+ "	FROM			ServiceSupplier user"
			+ "	WHERE			user.creditCode = :creditCode	";
	public boolean existCreditcode(String creditCode) {
		Query query = entityManager.createQuery(EXIST_CREDITCODE_EQL);
		query.setParameter("creditCode", creditCode);
		long count = (long)query.getSingleResult();
		if (count > 0) return true;
		else return false;
	}
	
	
	
}
